<template>
    <div class="map-area">
        <div class="option-tool">
            <div
                class="option-item"
                v-for="(item, index) in optionList"
                :key="index"
                @click="startDraw(item)"
                :class="item.active ? 'active' : ''"
            >
                {{ item.name }}
            </div>
            <div class="option-item" @click="handelRemoveDraw">移除</div>
        </div>
        <div class="map-container" id="mapContainer"></div>
    </div>
</template>
<script>
import * as leaflet from 'leaflet'
import 'leaflet/dist/leaflet.css'
import * as mars2d from 'mars2d'
import 'mars2d/dist/mars2d.css'
import * as turf from '@turf/turf'
let map = null
let drawLayer = null
let showLayer = null
export default {
    props: {
        // 回显
        values: {
            type: String,
            default: () => {
                return ''
            }
        }
    },
    data() {
        return {
            GIS_API: process.env.VUE_APP_GIS_HOST,
            optionList: [
                {
                    type: 'polygon',
                    active: false,
                    name: '面',
                    style: {
                        fill: false,
                        outline: true,
                        outlineWidth: 2,
                        outlineColor: '#FBC21A',
                        outlineOpacity: 1,
                        clampToGround: true
                    }
                },
                {
                    type: 'rectangle',
                    name: '矩形',
                    active: false,
                    style: {
                        fill: false,
                        outline: true,
                        outlineWidth: 2,
                        outlineColor: '#FBC21A',
                        outlineOpacity: 1,
                        clampToGround: true
                    }
                },
                {
                    type: 'circle',
                    name: '圆',
                    active: false,
                    style: {
                        fill: false,
                        outline: true,
                        outlineWidth: 2,
                        outlineColor: '#FBC21A',
                        outlineOpacity: 1,
                        clampToGround: true
                    }
                }
            ]
        }
    },
    mounted() {
        this.initMap()
        this.initEditLayer()
    },
    methods: {
        // 初始化地图
        initMap() {
            console.log('map', map)
            console.log('leaflet', leaflet)
            // let _this = this
            map = new mars2d.Map('mapContainer', {
                // crs: mars2d.CRS.EPSG4326,
                zoom: 4,
                center: {
                    lng: 105.908203,
                    lat: 36.386749
                },
                basemaps: [
                    // {
                    //     type: 'wmts',
                    //     name: '蓝色地图',
                    //     url:
                    //         _this.GIS_API +
                    //         '/geoserver/Ele_Map/gwc/service/wmts',
                    //     layer: 'Ele_Map:HH_Basemap',
                    //     format: 'image/png',
                    //     tileMatrixSetID: 'EPSG:4326', // 对应wmts请求的 tilematrixSet
                    //     tilematrixBefore: 'EPSG:4326:', // 对应wmts请求的 tilematrix
                    //     crs: 'EPSG:4326',
                    //     show: true
                    // }
                    {
                        name: '高德卫星',
                        type: 'group',
                        show: true,
                        layers: [
                            { name: '底图', type: 'gaode', layer: 'img_d' },
                            { name: '注记', type: 'gaode', layer: 'img_z' }
                        ]
                    }
                ],
                copyright: false
            })
            this.removeDrawLayer()
            drawLayer = new mars2d.layer.GraphicLayer({
                id: Date.now(),
                name: '绘制图层',
                hasEdit: true,
                isAutoEditing: false // 绘制完成后是否自动激活编辑
            })
            map.addLayer(drawLayer)
        },
        // 移除绘制图层
        removeDrawLayer() {
            if (drawLayer) {
                drawLayer.remove()
                drawLayer = null
            }
        },
        // 开始绘制
        startDraw(item) {
            this.optionList.forEach(ele => {
                ele.active = false
            })
            let _this = this
            item.active = true
            this.handelRemoveDraw()
            drawLayer && drawLayer.startDraw(item)
            // 绘制完成
            drawLayer.on(mars2d.EventType.drawCreated, function(e) {
                console.log('e', e)
                let center
                if (item.type === 'circle') {
                    center = e.graphic._latlng
                } else {
                    center = e.graphic.getCenter()
                }
                console.log('center', center)
                item.active = false
                let geojsonObject = drawLayer.toGeoJSON()
                if (geojsonObject == null) {
                    _this.$emit('AreaChange', null)
                    return null
                }
                geojsonObject = mars2d.Util.clone(geojsonObject)
                let area
                if (item.type === 'circle') {
                    area = e.graphic.radius * 3.14
                } else {
                    area = _this.calculateArea(geojsonObject)
                }
                _this.$emit('AreaChange', {
                    area: area,
                    center: center,
                    geojson: JSON.stringify(geojsonObject)
                })
            })
            // 开始编辑
            drawLayer.on(mars2d.EventType.editStart, function() {
                _this.optionList.forEach(ele => {
                    ele.active = false
                })
                item.active = true
            })
            // 编辑完成
            drawLayer.on(mars2d.EventType.editStop, function(e) {
                console.log('e', e)
                item.active = false
                let geojsonObject = drawLayer.toGeoJSON()
                if (geojsonObject == null) {
                    _this.$emit('AreaChange', null)
                    return null
                }
                geojsonObject = mars2d.Util.clone(geojsonObject)
                geojsonObject = mars2d.Util.clone(geojsonObject)
                let center
                if (item.type === 'circle') {
                    center = e.graphic._latlng
                } else {
                    center = e.graphic.getCenter()
                }
                console.log('center', center)
                let area
                if (item.type === 'circle') {
                    area = e.graphic.radius * 3.14
                } else {
                    area = _this.calculateArea(geojsonObject)
                }
                _this.$emit('AreaChange', {
                    center: center,
                    area: area,
                    geojson: JSON.stringify(geojsonObject)
                })
            })
        },
        // 移除所有图层
        handelRemoveDraw() {
            this.removeDraw()
            this.removeShowLayer()
        },
        // 移除绘制内容
        removeDraw() {
            drawLayer && drawLayer.clear()
            this.$emit('AreaChange', null)
        },
        // 移除回填内容
        removeShowLayer() {
            showLayer && showLayer.clear()
        },
        // 计算面积
        calculateArea(coors) {
            let polygon = turf.polygon(coors.features[0].geometry.coordinates)
            let area = turf.area(polygon, {
                units: 'meters'
            })
            return area
        },
        // 新增回显图层
        initEditLayer() {
            if (this.values && this.values !== '') {
                showLayer = new mars2d.layer.GeoJsonLayer({
                    name: '范围数据',
                    data: this.values,
                    hasEdit: false,
                    flyTo: true
                })
                map.addLayer(showLayer)
            } else {
                return
            }
        }
    },
    destroyed() {
        if (map) {
            map.eachLayer(layers => {
                map.removeLayer(layers)
            })
            map.destroy()
            map = null
        }
    }
}
</script>
<style lang="scss">
.map-area {
    @include box_flex(
        $width: 100%,
        $height: 100%,
        $direction: column,
        $justify: center,
        $align: center
    );
    .option-tool {
        @include box_flex(
            $width: 100%,
            $height: auto,
            $direction: row,
            $justify: flex-start,
            $align: center
        );
        padding-bottom: 10px;

        .option-item {
            @include box_flex(
                $width: auto,
                $height: auto,
                $direction: row,
                $justify: center,
                $align: center
            );
            @include border_color($color: 'border-base');
            padding: 5px 20px;
            margin-right: 20px;
            cursor: pointer;
            @include background_color('color-t');
            @include font_color('cover3');
            transition: all 0.3s;

            &:hover {
                @include background_color('primary-light1');
                @include border_color($color: 'primary-light1');
                @include font_color('color-w');
            }
        }
        .option-item.active {
            @include background_color('primary-light1');
            @include border_color($color: 'primary-light1');
            @include font_color('color-w');
        }
    }
    .map-container {
        @include box_flex(
            $width: 100%,
            $height: auto,
            $direction: row,
            $justify: center,
            $align: center,
            $flex-1: 1
        );
    }
}
</style>
